/* ------------------------------ */
// 多线程示例
// 
// 
/* ------------------------------ */

#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <vector>
#include <chrono>

// 共享的字符串变量
std::string shared_string;

// 互斥锁对象
std::mutex string_mutex;

// 写线程函数
void writer_thread(const std::string& data, int thread_id) {
    for (int i = 0; i < 5; ++i) {
        // 加锁，确保写操作的互斥性
        std::lock_guard<std::mutex> lock(string_mutex);
        std::cout << "Writer " << thread_id << " is writing: " << data << std::endl;
        shared_string = data;
        // 模拟写操作延迟
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

// 读线程函数
void reader_thread(int thread_id) {
    for (int i = 0; i < 10; ++i) {
        // 加锁，确保读操作的互斥性
        std::lock_guard<std::mutex> lock(string_mutex);
        std::cout << "Reader " << thread_id << " reads: " << shared_string << std::endl;
        // 模拟读操作延迟
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

int main() {
    // 创建写线程
    std::thread writer1(writer_thread, "Hello", 1);
    std::thread writer2(writer_thread, "World", 2);

    // 创建读线程
    std::thread reader1(reader_thread, 1);
    std::thread reader2(reader_thread, 2);

    // 等待所有线程完成
    writer1.join();
    writer2.join();
    reader1.join();
    reader2.join();

    return 0;
}